package com.quanshu.exchange.ui.gui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gyf.barlibrary.ImmersionBar;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.quanshu.change.login.entity.CountryFlagEntity;
import com.quanshu.change.tool.ReaseActivity;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.LoginInterface;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.CountDownTimerUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.HomePageActivity;
import com.quanshu.exchange.ui.widget.LoadingDialog;
import com.quanshu.shop.base.tool.BaseTool;
import com.quanshu.shop.base.view.BaseTitleBar;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 注册页面
 * Created by xiniu003 on 2017/11/28.
 */

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.area_show)
    TextView areaShow;
    @BindView(R.id.phone_input)
    EditText phoneInput;
    @BindView(R.id.code_input)
    EditText codeInput;
    @BindView(R.id.gain_code)
    TextView gainCode;
    @BindView(R.id.recommend_input)
    EditText recommendInput;
    @BindView(R.id.icon_area)
    ImageView iconArea;

    @BindView(R.id.register_submit)
    TextView registerSubmit;
    @BindView(R.id.login_title)
    BaseTitleBar loginTitle;
    @BindView(R.id.login_title_txt)
    TextView loginTitleTxt;
    @BindView(R.id.area_select)
    LinearLayout areaSelect;
    @BindView(R.id.login_phone)
    LinearLayout loginPhone;
    @BindView(R.id.get_code_fl)
    FrameLayout getCodeFl;
    @BindView(R.id.get_code_line)
    View getCodeLine;
    @BindView(R.id.login_pwd)
    ConstraintLayout loginPwd;
    @BindView(R.id.register_interview)
    LinearLayout registerInterview;
    @BindView(R.id.register_txt1_fl)
    FrameLayout registerTxt1Fl;
    @BindView(R.id.register_txt1)
    TextView registerTxt1;
    @BindView(R.id.go_login)
    ConstraintLayout goLogin;


    private String areaShowStr;
    private String phoneInputStr;
    private String codeInputStr;
    private String recommendInputStr;

    private CountryFlagEntity countryFlagEntity;
    private List<CountryFlagEntity> countryInfos;
    private Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        ReaseActivity.assistActivity(this);
        ButterKnife.bind(this);
        mContext = this;
        initListener();
    }

    private void initListener() {
        ImmersionBar.with(this).statusBarColor("#ffffff").statusBarDarkFont(true).titleBar(loginTitle).init();
        loginTitle.setRightImage(R.drawable.icon_login_close_2_0).setOnClickBaseTitleListener(new BaseTitleBar.OnClickBaseTitleBarListener() {
            @Override
            public void onclickLeft() {

            }

            @Override
            public void onclickRight() {
                BaseTool.goActivity(mContext, LoginActivity.class, null);
            }
        });

        RxViewHelper.getInstance().clicks(areaSelect, aVoid -> doGetCountries());
        RxViewHelper.getInstance().clicks(goLogin, aVoid -> {
            BaseTool.goActivity(mContext, LoginActivity.class, null);
        });

        RxViewHelper.getInstance().clicks(gainCode, aVoid -> doSendSms());

        RxViewHelper.getInstance().clicks(registerSubmit, aVoid -> {
            if (countryFlagEntity != null) {
                doRegister(countryFlagEntity);
            }
        });

        RxViewHelper.getInstance().afterTextChangeEvents(areaShow,
                textViewAfterTextChangeEvent -> {
                    areaShowStr = areaShow.getText().toString();
                    setViewState();
                });

        RxViewHelper.getInstance().afterTextChangeEvents(phoneInput,
                textViewAfterTextChangeEvent -> {
                    phoneInputStr = phoneInput.getText().toString();
                    setViewState();
                });

        RxViewHelper.getInstance().afterTextChangeEvents(codeInput,
                textViewAfterTextChangeEvent -> {
                    codeInputStr = codeInput.getText().toString();
                    setViewState();
                });

        RxViewHelper.getInstance().afterTextChangeEvents(recommendInput,
                textViewAfterTextChangeEvent -> {
                    recommendInputStr = recommendInput.getText().toString();
                });
        getCountryFlag();
    }

    private void doSendSms() {
        if (TextUtils.isEmpty(areaShowStr)) {
            ToastHelper.toast("请输入你的地区");
            return;
        } else if (TextUtils.isEmpty(phoneInputStr)) {
            ToastHelper.toast("请输入手机号码");
            return;
        }

        NetClient.getInstance()
                .getShopService(LoginInterface.class)
                .doSendSms(AppUtils.getSignParams(phoneInputStr), phoneInputStr)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        ToastHelper.toast(response.getMsg());
                        CountDownTimerUtils timerUtils = new CountDownTimerUtils(gainCode, 60000, 1000);
                        timerUtils.start();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }

    private void doRegister(CountryFlagEntity countryEntity1) {
        //注册按钮 - 跳转
        if (TextUtils.isEmpty(areaShowStr)) {
            ToastHelper.toast("请选择您所在国家");
            return;
        } else if (TextUtils.isEmpty(phoneInputStr)) {
            ToastHelper.toast("请输入手机号码");
            return;
        } else if (TextUtils.isEmpty(codeInputStr)) {
            ToastHelper.toast("请输入验证码");
            return;
        }
        NetClient.getInstance()
                .getShopService(LoginInterface.class)
                .doRegister(AppUtils.getSignParams(countryEntity1.getId(), phoneInputStr, codeInputStr, recommendInputStr),
                        countryEntity1.getId(), phoneInputStr, codeInputStr, recommendInputStr)
                .compose(new BaseTransformer<>(this, true, false))
                .subscribe(new BaseObserver<BaseResponse<UserEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<UserEntity> response) {
                        LoadingDialog loadingDialog = new LoadingDialog(RegisterActivity.this, false);
                        loadingDialog.show();
                        MyApplication.getInstance().setCurrentUser(response.getData());
                        MyApplication.getInstance().setToken(response.getToken());
                        doLoginEase(response.getData(), loadingDialog);
                    }
                });
    }

    private void setViewState() {
        if (areaShowStr != null && phoneInputStr != null && codeInputStr != null) {
            registerSubmit.setEnabled(true);
        } else {
            registerSubmit.setEnabled(false);
        }
    }

    private void doGetCountries() {
        if (countryInfos != null && countryInfos.size() > 0) {
            doShowCountriesDialog();
        } else {
            getCountryFlag();
            if (countryInfos != null && countryInfos.size() > 0){
                doShowCountriesDialog();
            }
        }
    }

    private void getCountryFlag() {
        NetClient.getInstance()
                .getShopService(LoginInterface.class)
                .getCountryList("")
                .compose(new BaseTransformer<>(this))
                .subscribe(response -> {
                    Log.d("获取国旗数据", "doGetCountries: " + response.getData().toString());
//                        countryInfos = AppUtils.formatData(response.getData());
                    countryInfos = response.getData();
                    if (countryInfos != null && countryInfos.size() > 0) {
                        for (int a = 0; a < countryInfos.size(); a++) {
                            if (Integer.valueOf(countryInfos.get(a).getId()) == 1) {
                                countryFlagEntity = countryInfos.get(a);
                            }
                        }
                    }

                });
    }

    private void doShowCountriesDialog() {
        DialogCountryList dialogCountryList = new DialogCountryList(this);
        dialogCountryList.show();
        dialogCountryList.setData(countryInfos);
        dialogCountryList.getItemClickSubject().subscribe(tmpCountryInfo -> {
            dialogCountryList.dismiss();
            countryFlagEntity = tmpCountryInfo;
            areaShow.setText(tmpCountryInfo.getCountry_name());
            Glide.with(this).load(Config.URL_HOST_SHOP + countryFlagEntity.getCountry_img()).into(iconArea);
        });
    }

    private void doLoginEase(UserEntity entity, LoadingDialog loadingDialog) {
        EMClient.getInstance().login(entity.getMemberid(), "123456", new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    Intent intent = new Intent(RegisterActivity.this, HomePageActivity.class);
                    startActivity(intent);
                    finish();
                });
            }

            @Override
            public void onError(int code, String error) {
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    ToastHelper.toast("注册失败=code" + code + "+error" + error);
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });
    }

}
